<template>
  <div class="bg-white rounded border border-gray-200 relative flex flex-col">
    <div class="px-6 pt-6 pb-5 font-bold border-b border-gray-200">
      <span class="card-title">{{ $t('manage.Upload') }}</span>
      <i class="fas fa-upload float-right text-green-400 text-2xl"></i>
    </div>
    <div class="p-6">
      <!-- Upload Dropbox -->
      <div
        class="w-full px-10 py-20 rounded text-center cursor-pointer border border-dashed border-gray-400 text-gray-400 transition duration-500 hover:text-white hover:bg-green-400 hover:border-green-400 hover:border-solid"
        :class="{ 'bg-green-400 border-green-400 border-solid': is_dragover }"
        @drag.prevent.stop=""
        @dragstart.prevent.stop=""
        @dragend.prevent.stop="is_dragover = false"
        @dragover.prevent.stop="is_dragover = true"
        @dragenter.prevent.stop="is_dragover = true"
        @dragleave.prevent.stop="is_dragover = false"
        @drop.prevent.stop="uploadFun($event)"
      >
        <h5>{{ $t('manage.drop') }}</h5>
      </div>
      <input type="file" multiple @change="uploadFun($event)" />
      <hr class="my-6" />
      <!-- Progess Bars -->
      <div class="mb-4" v-for="upload in uploads" :key="upload.name">
        <!-- File Name -->
        <div class="font-bold text-sm" :class="upload.text_class">
          <i :class="upload.icon"></i> {{ upload.name }}
        </div>
        <div class="flex h-4 overflow-hidden bg-gray-200 rounded">
          <!-- Inner Progress Bar -->
          <div
            :class="upload.variant"
            class="transition-all progress-bar"
            :style="{ width: `${upload.current_progress}%` }"
          ></div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { onBeforeUnmount, reactive, ref } from 'vue'
import { auth, storage, songsCollection } from '@/includes/firebase'
const is_dragover = ref(false)
const uploads = reactive([])
const emits = defineEmits(['addSong'])

const uploadFun = ($event) => {
  is_dragover.value = false
  // 兼容拖拽和点击input上传
  const files = $event.dataTransfer ? [...$event.dataTransfer.files] : [...$event.target.files]
  files.forEach((file) => {
    if (file.type !== 'audio/mpeg') return

    const storageRef = storage.ref() //类似oss 放到 music-d1dd2.appspot.com 这下面
    const songsRef = storageRef.child(`songs/${file.name}`) //上传名字 和位置
    const task = songsRef.put(file) //开始上传
    let uploadIndex =
      uploads.push({
        task, //后面取消上传要用
        current_progress: 0,
        name: file.name,
        variant: 'bg-blue-400',
        icon: 'fas fa-spinner fa-spin',
        text_class: ''
      }) - 1
    // 上传进度监听
    task.on(
      'state_changed',
      (snapshot) => {
        //   上传回调
        const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
        uploads[uploadIndex].current_progress = progress
      },
      (err) => {
        //   上传失败回调
        uploads[uploadIndex].variant = 'bg-red-400'
        uploads[uploadIndex].icon = 'fas fa-times'
        uploads[uploadIndex].text_class = 'text-red-400'
        console.log(err)
      },
      async () => {
        // 上传成功回调
        const song = {
          uid: auth.currentUser.uid, //记录id
          display_name: auth.currentUser.displayName, //上传的用户名
          original_name: task.snapshot.ref.name,
          modified_name: task.snapshot.ref.name,
          genre: '',
          comment_count: 0
        }
        song.url = await task.snapshot.ref.getDownloadURL() //拿到上传文件 的访问地址
        //   将上传文件相关信息 再存入到数据库---表中
        const songRef = await songsCollection.add(song)
        const songSnapshot = await songRef.get()
        //   将数据 传出去 songSnapshot
        // console.log('ddd', songSnapshot)
        emits('addSong', songSnapshot)

        //   样式状态变化
        uploads[uploadIndex].variant = 'bg-green-400'
        uploads[uploadIndex].icon = 'fas fa-check'
        uploads[uploadIndex].text_class = 'text-green-400'
      }
    )
  })
}
const cancelUploads = () => {
  uploads.forEach((upload) => {
    upload.task.cancel()
  })
}
onBeforeUnmount(cancelUploads)
</script>
